package com.duowei.dw_pos.dialog;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatDialogFragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.duowei.dw_pos.R;
import com.duowei.dw_pos.bean.PrintClear;
import com.duowei.dw_pos.bean.Xsfkfs;
import com.duowei.dw_pos.bean.Xsjbxx;
import com.duowei.dw_pos.httputils.DownHTTP;
import com.duowei.dw_pos.httputils.VolleyResultListener;
import com.duowei.dw_pos.sunmiprint.Prints;
import com.duowei.dw_pos.tools.Format;
import com.duowei.dw_pos.tools.Net;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import woyou.aidlservice.jiuiv5.IWoyouService;

/**
 * A simple {@link Fragment} subclass.
 */
public class ClearDialogFragment extends AppCompatDialogFragment {
    @BindView(R.id.jsj)
    TextView mJsj;
    @BindView(R.id.yhmc)
    TextView mYhmc;
    @BindView(R.id.count)
    TextView mCount;
    @BindView(R.id.ysje)
    TextView mYsje;
    @BindView(R.id.zk)
    TextView mZk;
    @BindView(R.id.ys)
    TextView mYs;
    Unbinder unbinder;
    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;
    @BindView(R.id.fjzcount)
    TextView mFjzcount;
    @BindView(R.id.sbsj)
    TextView mSbsj;
    @BindView(R.id.xbsj)
    TextView mXbsj;
    @BindView(R.id.ss)
    TextView mSs;
    @BindView(R.id.btn_clear)
    Button mBtnClear;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_detail)
    TextView mTvDetail;
    private String mPad;
    private String mYhbh;
    private String mYhmc1;
    private PrintClear mPrintData;

    private List<Xsfkfs> mXsfkfsList = new ArrayList<>();

    private IWoyouService woyouService;
    private Prints mPrinter;

    public ClearDialogFragment() {
        // Required empty public constructor
    }

    private ServiceConnection connService = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            woyouService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            woyouService = IWoyouService.Stub.asInterface(service);
        }
    };

    public static ClearDialogFragment newInstance(String pad, String yhbh, String yhmc) {
        Bundle args = new Bundle();
        args.putString("pad", pad);
        args.putString("yhbh", yhbh);
        args.putString("yhmc", yhmc);
        ClearDialogFragment fragment = new ClearDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPrinter = Prints.getPrinter();
        mPrinter.bindPrintService(getActivity(), connService);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_clear_dialog, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        mPad = getArguments().getString("pad");
        mYhbh = getArguments().getString("yhbh");
        mYhmc1 = getArguments().getString("yhmc", "");
        mJsj.setText("收银机号：" + mPad);
        mYhmc.setText("收银员  ：" + mYhmc1);
        final String sqlXsjbxx = "select CONVERT(varchar(100), GETDATE(), 120)as XBSJ,CONVERT(varchar(100),y.SBSJ,120)as SBSJ,x.* from xsjbxx x,ygsbbc y" +
                " where x.xh='" + mYhbh + "' and x.jysj between(select sbsj from ygsbbc where yhbh='" + mYhbh + "'" +
                " and by6='" + mPad + "' and (xbsj is null or xbsj='')) AND getdate() and x.bz='" + mPad + "'" +
                " and y.yhbh='" + mYhbh + "' and y.by6='" + mPad + "' and (y.xbsj is null or y.xbsj='')|";
        DownHTTP.postVolley6(Net.url, sqlXsjbxx, new VolleyResultListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), "网络异常", Toast.LENGTH_SHORT).show();
                mProgressBar.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(String response) {
                float jezj = 0f, zkje = 0f, ys = 0f, ss = 0f;
                if(response.toLowerCase().contains("error")){
                    Toast.makeText(getActivity(),response,Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!response.equals("]")) {
                    Xsjbxx[] xsjbxxes = new Gson().fromJson(response, Xsjbxx[].class);
                    for (int i = 0; i < xsjbxxes.length; i++) {
                        Xsjbxx xsjbxx = xsjbxxes[i];
                        jezj += xsjbxx.getJEZJ();
                        zkje += xsjbxx.getZKJE();
                        ys += xsjbxx.getYS();
                        ss += xsjbxx.getSS();
                    }
                    final String sbsj = xsjbxxes[0].getSBSJ().substring(5, xsjbxxes[0].getSBSJ().length());
                    String xbsj = xsjbxxes[0].getXBSJ().substring(5, xsjbxxes[0].getXBSJ().length());
                    mSbsj.setText("上班时间：" + sbsj);
                    mXbsj.setText("下班时间：" + xbsj);
                    mCount.setText("销售笔数：" + (xsjbxxes.length));
                    mYsje.setText("原价销售总额：￥" + Format.digitFormat2(jezj + ""));
                    mZk.setText("折扣金额：￥" + Format.digitFormat2(zkje + ""));
                    mYs.setText("应收金额：￥" + Format.digitFormat2(ys + ""));
                    mSs.setText("收现金额：￥" + Format.digitFormat2(ss + ""));
                    mPrintData = new PrintClear(mPad, mYhmc1, sbsj, xbsj, xsjbxxes.length, jezj, zkje, ys, ss);

                    String sqlXsfkfs = "select nr,sum(fkje)as fkje,sum(dyqzs)as dyqzs from xsfkfs where xsdh in(select x.xsdh from xsjbxx x,ygsbbc y where " +
                            "x.xh='" + mYhbh + "' and x.jysj between(select sbsj from ygsbbc where yhbh='" + mYhbh + "' " +
                            "and by6='" + mPad + "' and (xbsj is null or xbsj='')) AND getdate() and x.bz='" + mPad + "' " +
                            "and y.yhbh='" + mYhbh + "' and y.by6='" + mPad + "' and (y.xbsj is null or y.xbsj=''))group by nr order by fkje|";
                    DownHTTP.postVolley6(Net.url, sqlXsfkfs, new VolleyResultListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            mProgressBar.setVisibility(View.GONE);
                        }

                        @Override
                        public void onResponse(String response) {
                            if (!response.equals("]") && !response.toLowerCase().contains("error")) {
                                Gson gson = new Gson();
                                Type type = new TypeToken<List<Xsfkfs>>() {
                                }.getType();
                                mXsfkfsList = gson.fromJson(response, type);
                                String str="";
                                for (int i = 0; i < mXsfkfsList.size(); i++) {
                                    Xsfkfs xsfkfs = mXsfkfsList.get(i);
                                    if(TextUtils.isEmpty(xsfkfs.getDyqzs())||Float.parseFloat(xsfkfs.getDyqzs())<=0){
                                        str+= xsfkfs.getNr()+":￥"+xsfkfs.getFkje()+"\n";
                                    }else{
                                        str+= xsfkfs.getNr()+":￥"+xsfkfs.getFkje()+"    张数："+xsfkfs.getDyqzs()+"\n";
                                    }
                                }
                                mTvDetail.setText("非现金付款明细：\n"+str);
                            }
                            mProgressBar.setVisibility(View.GONE);
                        }
                    });
                } else {
                    mTvTitle.setText("没有结账数据");
                    mProgressBar.setVisibility(View.GONE);
                }
            }
        });
        return inflate;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        getActivity().unbindService(connService);
    }

    @OnClick({R.id.btn_exit, R.id.btn_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_exit:
                dismiss();
                getActivity().finish();
                break;
            case R.id.btn_clear:
                mProgressBar.setVisibility(View.VISIBLE);
                String sql = "update wmlsbjb set by7='1' where sfyjz='1' and jsj='" + mPad + "'|" +
                        " update ygsbbc set xbsj=getdate() where yhbh='" + mYhbh + "' and by6='" + mPad + "' and (xbsj is null or xbsj='')|";
                DownHTTP.postVolley7(Net.url, sql, new VolleyResultListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getActivity(), "网络异常", Toast.LENGTH_SHORT).show();
                        mProgressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onResponse(String response) {
                        if (response.contains("richado")) {
                            if(mPrintData!=null){
                                mPrinter.setWoyouService(woyouService);
                                mPrinter.print_Clear(mPrintData, mXsfkfsList);
                            }
                            dismiss();
                            getActivity().finish();
                            Toast.makeText(getActivity(), "清机成功", Toast.LENGTH_SHORT).show();
                        }
                        mProgressBar.setVisibility(View.GONE);
                    }
                });
                break;
        }
    }
}
